package com.powernode.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.powernode.reggie.common.R;
import com.powernode.reggie.entity.User;
import com.powernode.reggie.service.UserService;
import com.powernode.reggie.utils.MailUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @description:
 * @author: www
 * @time: 2023/3/15 15:00
 */
@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 发送邮箱验证码
     * @param user
     * @param session
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user , HttpSession session){
        String email = user.getPhone(); // 获取前端传来的用户邮箱

        if(email != null){//邮箱不为空在能继续
            //生成随机6位验证码
            String code = MailUtils.generateCode();
            log.info("code = {}:",code);

            //发送邮箱验证码
            //MailUtils.sendVerificationCode(email,code);

            //将生成的验证码保存到Session保存作用域，方便后面拿出来对比
            //session.setAttribute(email,code);

            //将生成的验证码缓存在redis中， 并且设置有效期为5分钟
            redisTemplate.opsForValue().set(email,code,5, TimeUnit.MINUTES);


            return R.success("邮箱验证码发送成功");
        }
        return R.error("邮箱验证码发送失败");
    }


    /**
     * 移动端用户登录，返回user对象给移动端，将user存入session
     * @param map
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session){
        log.info(map.toString());
        //获取前端email
        String email = map.get("phone").toString();

        //获取前端验证码
        String code = map.get("code").toString();

        //从session中获取保存的验证码
        //Object codeInSession = session.getAttribute(email);//key 是email

        //从redis 中取出缓存的验证码
        Object codeInSession = redisTemplate.opsForValue().get(email);


        //进行验证码比对（页面提交的验证码和session保存的而验证码比对)
        if(codeInSession != null && codeInSession.equals(code)){
            //比对成功，说明登录成功
            //判断的当前邮箱号对应的用户是否为新用户， 如果是新用户，自动将用户信息保存在用户表中完成注册
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,email);//查询条件，查找email在用户表中是否存在
            User user = userService.getOne(queryWrapper);

            if(user == null){//判断是新用户就将其邮箱号注册到数据库中
                user = new User();
                user.setPhone(email);
                userService.save(user);
            }
            session.setAttribute("user",user.getId());

            //如果用户登录成功，删除redis中缓存的验证码
            redisTemplate.delete(email);

            return R.success(user);
        }
        return R.error("登录失败");
    }
    /**
     * 员工退出
     * @param request
     * @return
     */
    @PostMapping("/loginout")
    public R<String> logout(HttpServletRequest request){
        //清理Session中保存的当前用户的id
        request.getSession().removeAttribute("user");
        return R.success("退出成功");
    }



}
